package com.softserveinc.interactive_board.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.softserveinc.interactive_board.domain.User;
import com.softserveinc.interactive_board.service.UserService;
import com.softserveinc.interactive_board.validators.form.EditUserForm;

@Controller
@RequestMapping("/registration")
public class RegistrationController {

	private static final String INDEX_FILE_LOCATION = "registration/index";

	private static final String EDIT_USERFORM_ATTR_NAME = "editUserForm";
	private static final String REDIRECTED_ATTR_NAME = "editUserForm";
	
	@RequestMapping(method = RequestMethod.GET)
	public String def() {
		return "redirect:/registration/";
	}

	@RequestMapping(method = RequestMethod.GET, value="/")
	public String def(Model model) {
		model.addAttribute(RegistrationController.REDIRECTED_ATTR_NAME, false);
		return "redirect:/registration/index";
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/index")
	public String index(@RequestParam(RegistrationController.REDIRECTED_ATTR_NAME) boolean redirected, Model model) {
		model.addAttribute(RegistrationController.REDIRECTED_ATTR_NAME, redirected);
		model.addAttribute(RegistrationController.EDIT_USERFORM_ATTR_NAME, new EditUserForm());
		return RegistrationController.INDEX_FILE_LOCATION;
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/index")
	public String index(Model model, @Valid final EditUserForm form, final BindingResult result) {
		if (result.hasErrors())
			return RegistrationController.INDEX_FILE_LOCATION;
		User user = form.getUser();
		if (!this.userService.addUser(user)) {
			model.addAttribute(RegistrationController.REDIRECTED_ATTR_NAME, true);
			return RegistrationController.INDEX_FILE_LOCATION;
		}
		return "redirect:/";
	}

	private UserService userService;

	@Autowired	
	@Qualifier("userServiceImpl")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
